<?php

require_once 'inc.php';


$dir = "../wallbase/images";
//$dir = "images";
$file_list = get_file_list($dir);

foreach ($file_list as $file)
{
	if (!file_exists($file) || !filesize($file)) contineu;
	image_colors_to_sql($file);
	/*if (empty($colors)) continue;

	echo $file;
	$counter = 0;
	foreach ($colors as $color => $count)
	{
		//if ($counter++ >= $color_limit) break;
		echo "\t".$color."|".$count;
	}*/
	
	echo $file."\n";

	//break;
}


function image_colors_to_sql($image_file)
{
	$image_p = imagecreatetruecolor(SAMPLE_BORDER_SIZE, SAMPLE_BORDER_SIZE);
	$image = get_image_from_file($image_file);
	if (!$image) return false;
	
	imagecopyresized($image_p, $image, 0, 0, 0, 0,
		SAMPLE_BORDER_SIZE, SAMPLE_BORDER_SIZE, imagesx($image), imagesy($image));
	imagetruecolortopalette2($image_p, false, 255);

	$hex_colors = array();
	for ($x=0; $x<SAMPLE_BORDER_SIZE; $x++)
	{
		for ($y=0; $y<SAMPLE_BORDER_SIZE; $y++)
		{
			$rgb = ImageColorsForIndex($image_p, imagecolorat($image_p, $x, $y));
			list($safe_r, $safe_g, $safe_b) = rgb2safe($rgb['red'], $rgb['green'], $rgb['blue']);

			$hex_color = sprintf("%02x%02x%02x", $safe_r, $safe_g, $safe_b);
			$hex_colors[$hex_color]++;
		}
	}

	arsort($hex_colors);
	
	$total_count = array_sum($hex_colors);
	
	$counter = 0;
	foreach ($hex_colors as $hex_color => $count)
	{
		if (++$counter > 20) break;
		//echo $color." -> ".$count/$total_count."<br>\n";continue;
		list($red, $green, $blue) = hex2rgb($hex_color);
		$sql = sys::getSqlString("insert into test_image_pallette (image_path, color_hex, ".
			"color_red, color_green, color_blue, percentage) values ('%s', '%s', '%d', '%d', '%d', '%f');",
			$image_file, $hex_color,
			$red, $green, $blue, $count/$total_count);
		sys::sql($sql);
	}
}
